package com.ccys.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.app.service.ContactUsScreenService;
import com.ccys.common.third.mailGun.MailgunUtil;
import com.ccys.common.util.HtmlUtils;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.SysCodeUtil;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.app.contactUsScreen.SendSupportDto;
import com.ccys.db.entity.TblFeedback;
import com.ccys.db.entity.TblMember;
import com.ccys.db.enums.SupportTypeEnum;
import com.ccys.db.mapper.TblFeedbackMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: WhiteCoat
 * @description: 联系我们接口
 * @author: ZhangJingCan
 * @create: 2024-01-29 15:53
 **/

@Service
public class ContactUsScreenServiceImpl implements ContactUsScreenService {

    /**
     * 对应对方的：tbl_Support表
     */
    @Resource
    private TblFeedbackMapper tblFeedbackMapper;

    @Override
    public ResponseResultApp sendSupport(SendSupportDto dto) throws Exception {
        TblMember member = UserUtil.getCurLoginMember();
        if (ObjectUtil.isEmpty(member)) {
            return ResponseResultApp.error(401, "Request require authorization.");
        }
        //根据传入的type获取对应的值
        Integer code = SupportTypeEnum.valueOf(dto.getContent_type()).getCode();
        //如果不存在 - 返回错误
        if (ObjectUtil.isEmpty(code)) {
            return ResponseResultApp.error(400, "Content type must is doctor feedback or consult feedback or general enquiries or app feedback or technical support or medication purchase");
        }
        //保存
        TblFeedback tblFeedback = new TblFeedback();
        tblFeedback.setContentType(code);
        tblFeedback.setContent(dto.getContent());
        tblFeedback.setMemId(member.getId());
        tblFeedbackMapper.insertSelective(tblFeedback);
        //判断当前所在国家是否有国家ID字段值
        if (ObjectUtil.isEmpty(member.getCurrentCountry())) {
            //设置国家ID为203
            member.setCurrentCountry("203");
        }
        String receiveCorporateBenefits = null;
        //判断当前所在国家id以及问题类型值
        if (member.getCurrentCountry().equals("245") && code == 7) {
            //需要去查询系统参数并设置值 - 并用 | 切割为字符串数组
            String[] split = SysCodeUtil.getCode("1", "Receive_Corporate_Benefits_VN").getValue().split("\\|");
            receiveCorporateBenefits = String.join(",", split);
        }


        String contentType = null;
        //这里需要一个首字母转大写的
        if (dto.getContent_type().equals("consult feedback")) {
            contentType = "Consult Feedback";
        } else if (dto.getContent_type().equals("general enquiries")) {
            contentType = "General Enquiries";
        } else if (dto.getContent_type().equals("app feedback")) {
            contentType = "App Feedback";
        } else if (dto.getContent_type().equals("technical support")) {
            contentType = "Technical Support";
        } else if (dto.getContent_type().equals("doctor feedback")) {
            contentType = "Doctor Feedback";
        } else if (dto.getContent_type().equals("medication purchase")) {
            contentType = "Medication Purchase";
        } else if (dto.getContent_type().equals("claim corporate rewards")) {
            contentType = "Claim Corporate Rewards";
        }

        //接收人邮箱
        String receiveSupportInfo = "Receive_Support_Info";
        if (member.getCurrentCountry().equals("106")) {
            receiveSupportInfo = "Receive_Support_Info_Indonesia";
        } else if (member.getCurrentCountry().equals("245")) {
            receiveSupportInfo = "Receive_Support_Info_Vietnam";
        } else if (member.getCurrentCountry().equals("106")) {
            receiveSupportInfo = "Receive_Support_Info_Malaysia";
        }
        //准备主题
        StringBuffer subject = new StringBuffer();
        subject.append("[WhiteCoat]").append(contentType).append(" from Whitecoat App - ").append(member.getFirstName() + (member.getLastName() != null ? member.getLastName() : ""));
        //发送邮件
        Map<String, Object> map = new HashMap<>();
        map.put("logoUrl", "https://s3-ap-southeast-1.amazonaws.com/content.whitecoat.global/emails/email-white-cost-logo.png");
        map.put("appName", "WhiteCoat");
        map.put("fullName", member.getFirstName() + (member.getLastName() != null ? member.getLastName() : ""));
        map.put("email", member.getEmail());
        map.put("nricFin", member.getNricFin());
        map.put("phone", member.getPhone());
        map.put("content", dto.getContent());
        //todo 这里的地址或许需要修改 对方是：ConfigurationManager.AppSettings["CMS_URL"].ToString(); 这样获取的第一节
        map.put("cmslink", "https://whcapi-qa.whitecoat.global/v1/member_detail.aspx?member=" + "加密之后的memberId");//Core_App.BL.QueryStringEncryption.Encrypt(mem_id);
        String templateContent = HtmlUtils.getTemplateContent("SendSupport.ftl", map);
        //接收人邮箱 - 某个国家的管理员设置的邮箱 - 如果有多个则使用|分割
        String[] emails = SysCodeUtil.getCode("1", receiveSupportInfo).getValue().split("\\|");
        String emailStr = String.join(",", emails);
        //不同的判断给不同的邮箱发送邮件
        if (ObjectUtil.isNotEmpty(contentType) && contentType.equals("Medication Purchase")) {
            MailgunUtil.sendEmail(emailStr, subject.toString(), null, templateContent);
        }else if (ObjectUtil.isNotEmpty(contentType) && contentType.equals("Claim Corporate Rewards")){
            //如果是越南
            if (member.getCurrentCountry().equals("245")){
                if (ObjectUtil.isNotEmpty(receiveCorporateBenefits)){
                    MailgunUtil.sendEmail(receiveCorporateBenefits, subject.toString(), null, templateContent);
                }
            }else {
                //todo 这里根据环境切换 - 当前为dev
                MailgunUtil.sendEmail(MailgunUtil.QA_DEV_EMAIL, subject.toString(), null, templateContent);
            }
        }else {
            MailgunUtil.sendEmail(receiveSupportInfo.split("\\|")[0], subject.toString(), null, templateContent);
        }


        return ResponseResultApp.success("Support feedback successful",null);
    }

}
